using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ISB_iCard
{
    public partial class iCardMain : Form
    {
        public iCardMain()
        {
            InitializeComponent();
        }

        //iCardService.Service1 objiCardService = new ISB_iCard.iCardService.Service1();
        string wsURL = string.Empty;
        WSUtility objwsUtil = new WSUtility();
        iCardService.Result objResult = new ISB_iCard.iCardService.Result();
        public string userid = "0";//This is the Login id of the steward.
        bool flagInstituteScaned = false; //This vairable is used to pass the cursor to the TransactionId text box to scan the barcode.
        bool isOfflineTxn = false;
        //string OfflineImage = "Offline.gif";
        //string OnlineImage = "Online.gif";
        private void Form1_Load(object sender, EventArgs e)
        {
            wsURL = Convert.ToString(MobileConfiguration.Settings["WSURL"]);
            this.KeyDown += new KeyEventHandler(this.OnKeyDown);
            lblDate.Text = DateTime.Now.ToString("dd-MMM-yy") + " " + DateTime.Now.ToShortTimeString();
            btnShowItems.Enabled = false;
            objwsUtil.URL = "http://192.168.2.135/ISBVS2008/Service1.asmx";
            if (Utility.CheckWiFi())
                pictureBox1.Image = Properties.Resources.Online;
            else
            {
                pictureBox1.Image = Properties.Resources.Offline;
                txtAmount.ReadOnly = false;
            }
        }

        private bool CheckWiFi()
        {
            if (Utility.CheckWiFi())
            {
                pictureBox1.Image = Properties.Resources.Online;
                return true;
            }
            else
            {
                pictureBox1.Image = Properties.Resources.Offline;
                return false;
            }
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F1:
                    if (CheckWiFi())
                        btnShowItems_Click(sender, e);
                    else
                        MessageBox.Show("NW Not available.");
                    break;

                case Keys.F2:
                    btnFetch_Click(new Object(), new EventArgs());
                    break;

                case Keys.F3:
                    btnCancel_Click(new Object(), new EventArgs());
                    break;

                case Keys.F4:
                    btnSubmit_Click(new object(), new EventArgs());
                    break;
                case Keys.F5:
                    rbtnTxnByCard.Checked = true;
                    flagInstituteScaned = false;
                    //rbtnTxnByCard_CheckedChanged(new object(), new EventArgs());
                    break;
                case Keys.F6:
                    rbtnTxnByCash.Checked = true;
                    //rbtnTxnByCash_CheckedChanged(new object(), new EventArgs());
                    break;

                case Keys.ControlKey:
                    /*Here when the SCAN button is pressed on the device, the readonly property of the InstituteId field is removed 
                      and the focus is set to the field, so that the barcode can be captured. Once the barcode is captured KeyUp event of the 
                      txtInstituteId is fired the flag "flagInstituteScaned" is set to true, so that next time the SCAN button is pressed the 
                      control is transfered to TxnId field.*/
                    if (rbtnTxnByCard.Checked && flagInstituteScaned == false)
                    {
                        txtInstituteId.Text = string.Empty;
                        txtInstituteId.ReadOnly = false;
                        //btnFetch.Enabled = true;
                        txtInstituteId.Focus();
                    }
                    else
                    { txtTxnId.Focus(); }
                    break;

                case Keys.V:
                    System.Threading.Thread.Sleep(10);
                    break;

                case Keys.Escape:
                    DialogResult objDilogResult = MessageBox.Show("Do you want to exit?", "ISB iCard.", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                    if (objDilogResult == DialogResult.Yes)
                        Application.Exit();
                    break;

                //default:
                //    MessageBox.Show(e.KeyCode.ToString() + " pressed.", "Key Down Event");
                //    break;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (rbtnTxnByCard.Checked)
                rbtnTxnByCard_CheckedChanged(sender, e);
            else if (rbtnTxnByCash.Checked)
                rbtnTxnByCash_CheckedChanged(sender, e);
            ClearControls();
            btnShowItems.Enabled = true;
            //btnShowItems.Enabled = false;
            //btnFetch.Enabled = true;
            btnSubmit.Enabled = true;
            txtTxnId.Focus();
            if (rbtnTxnByCard.Checked)
                offlineCard();
            else
                offlineCash();
        }

        void ClearControls()
        {
            txtInstituteId.Text = "Press SCAN to scan Id";
            txtTxnId.Text = string.Empty;
            txtAmount.Text = string.Empty;
            txtTendAmount.Text = string.Empty;
            txtBalAmount.Text = string.Empty;
            flagInstituteScaned = false;
            //btnShowItems.Enabled = false;
        }

        private void txtInstituteId_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.ControlKey:
                    //(Keys.LButton | Keys.MButton | Keys.ShiftKey |Keys.Space)
                    //txtInstituteId.Text = "61310651";
                    statusBar1.Text = "Data Captured, Press F4.";
                    btnShowItems.Enabled = true;
                    txtInstituteId.ReadOnly = true;
                    //btnFetch.Enabled = true;
                    txtTxnId.Focus();
                    flagInstituteScaned = true;
                    break;
            }
        }

        private void btnFetchAmount()
        {
            //if (btnFetch.Enabled)
            {
                try
                {
                    //btnFetch.Enabled = false;
                    statusBar1.Text = "Fetching data";
                    statusBar1.Refresh();
                    //objwsUtil.URL = "http://192.168.2.112/ISB_Data/Service1.asmx";
                    //objiCardService.Url = "http://172.16.0.248/ISB_Data/Service1.asmx";
                    //objiCardService.Url = "http://172.18.8.64:81/ISB_Data/Service1.asmx";
                    //MessageBox.Show(objiCardService.Url);
                    string Amount = objwsUtil.GetAmountByTxn(txtTxnId.Text);

                    if (Amount == string.Empty)
                    {
                        throw new Exception("Txn details not found.");

                    }
                    else
                    {
                        txtAmount.Text = Amount;
                        btnShowItems.Enabled = true;
                        btnSubmit.Enabled = true;
                        statusBar1.Text = "Done fetching data";
                        if (rbtnTxnByCash.Checked)
                            txtTendAmount.Focus();
                    }
                }
                catch (Exception ex)
                {
                    statusBar1.Text = "Error fetching data";
                    //MessageBox.Show("Error: " + ex.Message);
                    throw ex;
                }
            }
            //else
            //    statusBar1.Text = "Fetch amount is not enabled";
        }

        private void btnShowItems_Click(object sender, EventArgs e)
        {
            statusBar1.Text = "Please wait loading Items...";
            statusBar1.Refresh();
            try
            {
                if (btnShowItems.Enabled)
                {
                    if (txtTxnId.Text.Equals(string.Empty))
                        throw new Exception("Please Enter Txn Id");
                    TnxDetails objTxnDetails = new TnxDetails();
                    objTxnDetails.TxnId = txtTxnId.Text;
                    //objTxnDetails.strAmount = txtAmount.Text;
                    objTxnDetails.Show();
                    statusBar1.Text = "Ready";
                }
                else
                    statusBar1.Text = "Show Items is not enabled";
            }
            catch (Exception ex)
            {
                statusBar1.Text = "Error showing items.";
                MessageBox.Show("Error: " + ex.Message);
                btnCancel_Click(sender, e);
            }
        }

        private void txtTxnId_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    //btnFetch_Click(sender, e);
                    btnSubmit_Click(sender, e);
                    break;
            }
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnSubmit.Enabled)
                {
                    if (Utility.CheckWiFi() == false)
                    {
                        isOfflineTxn = true;
                        objwsUtil.IsOnline = false;
                        pictureBox1.Image = Properties.Resources.Offline;
                    }
                    else
                    {
                        isOfflineTxn = false;
                        objwsUtil.IsOnline = true;
                        pictureBox1.Image = Properties.Resources.Online;
                    }
                    long txnId = 0;
                    double amount = 0.00;
                    if (txtTxnId.Text.Equals(string.Empty))
                        throw new Exception("Please Enter Txn Id");
                    try
                    {
                        txnId = long.Parse(txtTxnId.Text);
                    }
                    catch (Exception)
                        { throw new Exception("Invalid Txn ID."); }



                    //if(MessageBox.Show("Total Amount: " + txtAmount.Text + ".", "Do you want to continue?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)
                    //objiCardService.Url = "http://172.16.0.248/ISB_Data/Service1.asmx";
                    //objiCardService.Url = "http://192.168.2.4/ISB_Data/Service1.asmx";
                    //btnFetch_Click(sender, e);
                    

                    if (!isOfflineTxn)
                    {
                        btnFetchAmount();
                        if (txtAmount.Text.Equals(string.Empty))
                            throw new Exception("Please Enter Amount");
                        try
                        {
                            amount = double.Parse(txtAmount.Text);
                        }
                        catch (Exception)
                        { throw new Exception("Invalid Amount."); }
                    }
                    else
                    {
                        if (txtAmount.Text.Equals(string.Empty))
                            throw new Exception("Please Enter Amount");

                        if (txtTendAmount.Text.Equals(string.Empty) && rbtnTxnByCash.Checked)
                            throw new Exception("Please Tendered Enter Amount");
                        try
                        {
                            amount = double.Parse(txtAmount.Text);
                        }
                        catch (Exception)
                        { throw new Exception("Invalid Tend Amount."); }
                    }
                    DialogResult objDilogResult = MessageBox.Show("Amount: " + amount.ToString("0.00") + ".", "Txn Information", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                    if (objDilogResult == DialogResult.Yes)
                    {
                        btnShowItems.Enabled = false;

                        if (txtAmount.Text.Length > 0)
                        {
                            if (rbtnTxnByCard.Checked)
                            {
                                statusBar1.Text = "Processing Txn...";
                                btnSubmit.Enabled = false;
                                if (txtInstituteId.Text.Equals("Press SCAN to scan Id"))
                                    txtInstituteId.Text = "0";
                                objResult = objwsUtil.PerformHHTransaction(Convert.ToInt64(txtTxnId.Text), txtInstituteId.Text, Convert.ToString(userid), amount, 0);
                                if (objResult.IsSuccess.Equals(false))
                                {
                                    throw new Exception(objResult.ErrorMessage);
                                }
                                statusBar1.Text = "Txn done.";
                                statusBar1.Refresh();
                                btnSubmit.Enabled = true;
                            }
                            else
                            {
                                btnSubmit.Enabled = false;
                                statusBar1.Text = "Processing Txn...";
                                statusBar1.Refresh();
                                objResult = objwsUtil.PerformHHTransaction(Convert.ToInt64(txtTxnId.Text), string.Empty, Convert.ToString(userid), amount, 1);
                                if (objResult.IsSuccess.Equals(false))
                                {
                                    throw new Exception(objResult.ErrorMessage);
                                }
                                if (txtTendAmount.Text.Length > 0)
                                {
                                    decimal x = Convert.ToDecimal(txtTendAmount.Text) - Convert.ToDecimal(txtAmount.Text);
                                    txtBalAmount.Text = x.ToString();
                                }
                                MessageBox.Show("Balance: " + txtBalAmount.Text);
                                btnSubmit.Enabled = true;
                                statusBar1.Text = "Txn Done.";
                                statusBar1.Refresh();
                            }
                            MessageBox.Show("Txn Done.");
                            btnCancel_Click(sender, e);
                        }
                        //else
                        //{
                        //    statusBar1.Text = "Please press F2.";
                        //}
                    }
                    else
                        ClearControls();
                }
                else
                    statusBar1.Text = "Submit not enabled";
            }
            catch (Exception ex)
            {
                statusBar1.Text = "Error, Please try again.";
                MessageBox.Show("Error Occurred: " + ex.Message);
                btnCancel_Click(sender, e);
            }
        }

        private void rbtnTxnByCard_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnTxnByCard.Checked)
            {
                ClearControls();
                btnShowItems.Enabled = false;
                txtTendAmount.ReadOnly = true;
                txtAmount.ReadOnly = true;
                txtTendAmount.ReadOnly = true;
                //btnSubmit.Enabled = false;
                if (Utility.CheckWiFi())
                {
                    //txtAmount.TabStop = false;
                    txtAmount.ReadOnly = true;
                    objwsUtil.IsOnline = true;
                    pictureBox1.Image = Properties.Resources.Online;
                }
                else
                {
                    //txtAmount.ReadOnly = false;
                    //txtAmount.TabStop = true;
                    objwsUtil.IsOnline = false;
                    pictureBox1.Image = Properties.Resources.Offline;
                    offlineCard();
                }
                txtTendAmount.ReadOnly = true;
                //txtInstituteId.Text = "Press SCAN to scan Id";
                    //txtInstituteId.Text = "61310651";
                statusBar1.Text = "Press SCAN to scan Id";
            }
        }
        public void offlineCard()
        {
            btnShowItems.Enabled = false;
            txtAmount.Text = "0";
            txtAmount.ReadOnly = true;
        }

        public void offlineCash()
        {
            btnShowItems.Enabled = false;
            txtAmount.Text = "0";
            txtAmount.ReadOnly = true;
            txtTendAmount.Text = "0";
            txtTendAmount.ReadOnly = true;
        }

        private void rbtnTxnByCash_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnTxnByCash.Checked)
            {
                ClearControls();
                //btnShowItems.Enabled = true;
                //txtAmount.ReadOnly = false;
                //btnFetch.Enabled = true;
                btnSubmit.Enabled = true;
                
                txtTendAmount.ReadOnly = false;
                if (Utility.CheckWiFi())
                {
                    btnShowItems.Enabled = true;
                    //txtAmount.TabStop = false;
                    txtAmount.ReadOnly = true;
                    objwsUtil.IsOnline = true;
                    pictureBox1.Image = Properties.Resources.Online;
                }
                else
                {
                    btnShowItems.Enabled = false;
                    //txtAmount.TabStop = true;
                    objwsUtil.IsOnline = false;
                    pictureBox1.Image = Properties.Resources.Offline;
                    offlineCash();
                }
                txtTxnId.Focus();
                txtInstituteId.Text = "Institute Id is disabled.";
                statusBar1.Text = "Enter TxnId and press F2";
            }
        }

        private void txtTendAmount_TextChanged(object sender, EventArgs e)
        {
            if (!isOfflineTxn)
            {
                //if (txtTendAmount.Text.Length > 0)
                //{
                //    decimal x = Convert.ToDecimal(txtTendAmount.Text) - Convert.ToDecimal(txtAmount.Text);
                //    txtBalAmount.Text = x.ToString();
                //}
                //else
                //    txtBalAmount.Text = string.Empty;
            }
            //else
            //{
            //    txtAmount.Text = "0.00";
            //}
        }

        private void btnFetch_Click(object sender, EventArgs e)
        {
            btnFetch.Enabled = false;
            PendingTxns obj = new PendingTxns();
            obj.Show();
            btnFetch.Enabled = true;
        }
    }
}